/**
 * Writed by yura and mak
 */

package wz.legend.handlers.steps;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import wz.legend.Context;
import wz.legend.HttpContext;
import wz.legend.Status;
import wz.legend.util.ScriptStarter;
import wz.legend.util.UriConstants;


public class ClickingChatStep extends AbstractStep {

    private static final Logger LOG = Logger.getLogger(ClickingChatStep.class);

    String actionName = null;
    String waitString = null;
    long timeout = 30000;
    long startTime = 0;

    public ClickingChatStep() {

    }

    public void execute(Context context) {
        LOG.debug("ClickingChatStep START");
        context.getScriptStater().doScript(actionName);
        if (state == State.UNKNOWN) {
            startTime = System.currentTimeMillis();
        }
        state = State.START;
        LOG.debug("ClickingChatStep execute");
    }

    public void handle(HttpContext httpContext, Context context) {
        try {
            if (httpContext != null) {
                String uri = httpContext.getRequest().getRequestLine().getUri();
                if (uri.contains(UriConstants.AREA_PHP) && state == State.START) {
                    LOG.debug("ClickingChatStep ACTIVE");
                    state = State.ACTIVE;
                }
                if (uri.contains(UriConstants.CHAT_DATA_PHP)
                        && (state == State.START || state == State.ACTIVE)) {
                    String content = IOUtils.toString(httpContext.getResponse()
                            .getEntity().getContent());
                    if (content.contains(waitString)) {
                        LOG.debug("ClickingChatStep STOPED");
                        state = State.STOPED;
                    }
                    if (state != State.STOPED
                            && startTime + timeout < System.currentTimeMillis()) {
                        LOG.debug("ClickingChatStep timeout goto inactive");
                        context.setStatus(Status.INACTIVE);
                        reset();
                    }
                }
            }
        } catch (Exception e) {
            LOG.error(e, e);
            throw new RuntimeException(e);
        }
    }

    public String getActionName() {
        return actionName;
    }

    public void setActionName(String actionName) {
        this.actionName = actionName;
    }

    public String getWaitString() {
        return waitString;
    }

    public void setWaitString(String waitString) {
        this.waitString = waitString;
    }

    public long getTimeout() {
        return timeout;
    }

    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }
}
